﻿Imports System.IO
Imports System.Configuration
Imports Microsoft.Win32
Imports System.Threading
Imports System.Management
Imports System.ServiceProcess
Imports Microsoft.Win32.Registry
Public Class frmConfig
#Region "Process - streamreaders/writers and events"
    Public Enum eConfigError
        Succes = 0
        UserName = 1
        Team = 2
        Passkey = 3
        AskNet = 4
        UseProxy = 5
        ProxyHost = 6
        ProxyPort = 7
        UseProxyPassword = 8
        ProxyUserName = 9
        ProxyPassword = 10
        WuSize = 11
        AddRemoveService = 12
        CorePriority = 13
        CpuUsage = 14
        DisableAssembly = 15
        PauseBattery = 16
        CPInterval = 17
        MemIndication = 18
        IgnoreDeadline = 19
        MachineID = 20
        CpuAffinity = 21
        Parameters = 22
        IPadress = 23
        AdvMethods = 24
    End Enum
    Private _Cerror As eConfigError = eConfigError.Succes
    Private cancelprocessing As Boolean = False
    Public WithEvents pConfigure As New Process
    Public pWriter As StreamWriter, pReader As StreamReader
    Delegate Sub Addoutput(ByVal [text] As String)
    Private rString As String = vbNullString
    Private _IsRunning As Boolean = False
    Public Class sPGroup
        Public Enum eType
            CoreFirst = 1
            ServiceFirst = 2
        End Enum
        Public Enum eAddRemove
            Keep = 0
            Manual = 1
            Service = 2
        End Enum
        Private _cType As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eClient
        Public Property GUIType() As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eClient
            Get
                Return _cType
            End Get
            Set(ByVal value As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eClient)
                _cType = value
            End Set
        End Property
        Private _AddRemove As eAddRemove
        Public Property ServiceCheck() As eAddRemove
            Get
                Return _AddRemove
            End Get
            Set(ByVal value As eAddRemove)
                _AddRemove = value
            End Set
        End Property
        Private _IsService As Boolean = False
        Public ReadOnly Property ServiceMode() As Boolean 'To determine gui display options
            Get
                Try
                    Dim sString As String
                    If _cType < 5 Then
                        sString = "Folding@Home-CPU-[" & MachineID & "]"
                    Else
                        sString = "Folding@Home-GPU-[" & MachineID & "]"
                    End If
                    Dim rKey As RegistryKey = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Services")
                    Dim sVal() As String = rKey.GetSubKeyNames
                    For Each sSer As String In sVal
                        If sSer.ToUpper = sString.ToUpper Then
                            Return True
                        End If
                    Next
                    Return False
                Catch ex As Exception
                    Debug.Print(ex.Message)
                    Return Nothing
                End Try
            End Get
        End Property
        Public ClientType As eType
        Public Name As String
        Public Team As String
        Public PassKey As String
        Public AskNet As String
        Public UseProxy As String
        Public UseProxyPass As String
        Public ProxyName As String
        Public ProxyPort As String
        Public ProxyUserName As String
        Public ProxyPassword As String
        Public WUSize As String
        Public CorePriority As String
        Public CpuUsage As String
        Public DissableAssembly As String
        Public PauseBattery As String
        Public CPInterval As String
        Public MemoryIndication As String
        Public AdvMethods As String
        Public IgnoreDeadline As String
        Public MachineID As String
        Public AddRemoveService As String
        Public DisableAffinty As String
        Public Parameters As String
        Public IPadress As String
        'End first section
    End Class
    Private pGR As New sPGroup
    Private pgW As New sPGroup
    Private pgBackUp As New sPGroup
    Public Property PandeGroup() As sPGroup
        Get
            Return pGR
        End Get
        Set(ByVal value As sPGroup)
            pGR = value
        End Set
    End Property
    ReadOnly Property pRunning() As Boolean
        Get
            Return _IsRunning
        End Get
    End Property
    Private Sub SetStartUpInfo()
        Try
Reset:
            _SMPerror = False
            _ConfigOutputReady = False
            rtf.Text = ""
            Application.DoEvents()
            pConfigure = New Process
            With pConfigure.StartInfo
                .FileName = Me.Client.GuiController.ClientEXE
                .Arguments = "-configonly"
                .UseShellExecute = False
                .CreateNoWindow = True
                .WorkingDirectory = Me.Client.GuiController.ClientLocation
                .RedirectStandardInput = True
                .RedirectStandardOutput = True
                .StandardOutputEncoding = System.Text.Encoding.Default
            End With
            pConfigure.Start()
            _ShouldRun = True
            _IsRunning = True
            pWriter = pConfigure.StandardInput
            pConfigure.BeginOutputReadLine()
            While Not rtf.Text.ToUpper.Contains("CONFIGURING FOLDING@HOME") And Not _SMPerror
                WaitMS(5)
                If pConfigure.HasExited Then
                    MsgBox("The console seems to have exited, press ok to repeat current operation.", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Unexpected exit")
                    GoTo Reset
                End If
            End While
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
        End Try
    End Sub
    Private Sub pConfigure_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles pConfigure.Disposed
        _IsRunning = False
    End Sub
    Private Sub pConfigure_ErrorDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles pConfigure.ErrorDataReceived
        If rtf.InvokeRequired Then
            rString = e.Data
            Dim tSafe As New Addoutput(AddressOf AddRtfOutput)
            Me.Invoke(tSafe, New Object() {[rString]})
        Else
            rtf.Text = rtf.Text & DateTime.Now.ToLongTimeString & " - " & e.Data & vbNewLine
        End If
    End Sub
    Private Sub pConfigure_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles pConfigure.Exited
        _IsRunning = False
    End Sub
    Private Shared _SMPerror As Boolean = False
    Private Sub pConfigure_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles pConfigure.OutputDataReceived
        Try
            If e.Data.ToUpper.Contains("CONFIGONLY FLAG GIVEN") Then
                _ConfigOutputReady = True
                _ShouldRun = False
            ElseIf e.Data.ToUpper.Contains("PLEASE CHECK YOUR CONFIGURATION") Or e.Data.ToUpper.Contains("SOCK ERROR") Then
                _ConfigOutputReady = True
                _ShouldRun = False
                _SMPerror = True
            End If
        Catch ex As Exception
        End Try
        Try
            If rtf.InvokeRequired Then
                rString = e.Data
                Dim tSafe As New Addoutput(AddressOf AddRtfOutput)
                Me.Invoke(tSafe, New Object() {[rString]})
            Else
                rtf.Text = rtf.Text & e.Data & vbNewLine
            End If
        Catch ex As Exception
        End Try

    End Sub
    Private Shared _ConfigOutputReady As Boolean = False
    Private Sub AddRtfOutput(ByVal [text] As String)
        rtf.Text = rtf.Text & DateTime.Now.ToLongTimeString & " - " & [text] & vbNewLine
    End Sub
    Public _ShouldRun As Boolean = False
    Public _bAskNet As Boolean = True
    Public _bServiceError As Boolean = False
    Private Sub ReadSettings(Optional ByVal DoGui As Boolean = True)
        Dim sOldS As String = lblS.Text
        gbC.Enabled = False
        gbKeep.Enabled = False
        lblS.Text = "Getting standard settings!"
        Application.DoEvents()
        Try
Restart:
            If _IsRunning Then Exit Sub
            SetStartUpInfo()
            'newline for reading up to advanced options
            While Not pConfigure.HasExited
                pWriter.WriteLine("")
                WaitMS(50)
            End While
            While Not _ConfigOutputReady
                Application.DoEvents()
                If Not _IsRunning And _ShouldRun = True Then
                    MsgBox("The console seems to have exited with an error, when you press OK the current operation will be repeated")
                    _ShouldRun = False
                    GoTo Restart
                End If
            End While
            WaitMS(50)
            If rtf.Text.ToUpper.Contains("PLEASE CHECK YOUR CONFIGURATION") Or rtf.Text.ToUpper.Contains("SOCK ERROR") Then
                _SMPerror = True
                GoTo NoSMP
            End If
            'Check is ask net is in text? 
            _bAskNet = rtf.Text.ToUpper.Contains("ASK BEFORE FETCHING/SENDING WORK")
            'Check current settings
            Dim vString As String = rtf.Text.ToString 'Getting values as enterd
            Dim pStart As Integer = vString.ToUpper.IndexOf("CONFIGURING FOLDING@HOME")
            Dim pEnd As Integer = vString.ToUpper.IndexOf("CONFIGONLY FLAG GIVEN")
            Dim HasAdvanced As Boolean = (vString.ToUpper.IndexOf("CORE PRIORITY") <> -1)
            vString = Mid(vString, pStart)
            If pStart = 0 Or pEnd = 0 Then
                'MsgBox("error")
                Me._Done = True
                Me.Close()
                Exit Sub
            ElseIf vString.ToUpper.IndexOf("USER NAME") <> 0 Then
                Dim uLen As Integer
                'name
                Dim uS1 As Integer = vString.ToUpper.IndexOf("USER NAME") + Len("user name")
                Dim uS2 As Integer = vString.IndexOf("[", uS1)
                Dim uE As Integer = vString.IndexOf("]", uS2)
                If Not uE - uS2 = 1 Then
                    uS2 = uS2 + 2
                    uLen = (uE - uS2) + 1
                    pGR.Name = Mid(vString, uS2, uLen)
                End If
                pStart = uS2
                'team
                uS1 = vString.ToUpper.IndexOf("TEAM NUMBER", pStart) + Len("team number")
                uS2 = vString.IndexOf("[", uS1)
                uE = vString.IndexOf("]", uS2)
                If Not uE - uS2 = 1 Then
                    uS2 = uS2 + 2
                    uLen = (uE - uS2) + 1
                    pGR.Team = Mid(vString, uS2, uLen)
                Else
                    pGR.Team = ""
                End If
                pStart = uS2
                'key
                uS1 = vString.ToUpper.IndexOf("PASSKEY", pStart)
                uS2 = vString.IndexOf("[", uS1)
                uE = vString.IndexOf("]", uS2)
                If Not uE - uS2 = 1 Then
                    uS2 = uS2 + 2
                    uLen = (uE - uS2) + 1
                    pGR.PassKey = Mid(vString, uS2, uLen)
                Else
                    pGR.PassKey = ""
                End If
                pStart = uS2
                If _bAskNet Then
                    'asknet
                    uS1 = vString.ToUpper.IndexOf("FETCHING/SENDING", pStart) + Len("fetching/sending")
                    uS2 = vString.IndexOf("[", uS1) + 2
                    uE = vString.IndexOf("]", uS2)
                    uLen = (uE - uS2) + 1
                    pGR.AskNet = Mid(vString, uS2, uLen)
                    pStart = uS2
                Else
                    pGR.AskNet = ""
                End If
                'UsePRoxy
                uS1 = vString.ToUpper.IndexOf("USE PROXY", pStart) + Len("USE PROXY")
                If vString.IndexOf("?", uS1) > vString.IndexOf("[", pStart) Then
                    pGR.UseProxy = "no"
                Else
                    uS2 = vString.IndexOf("[", uS1) + 2
                    uE = vString.IndexOf("]", uS2)
                    uLen = (uE - uS2) + 1
                    pGR.UseProxy = Mid(vString, uS2, uLen)
                End If
                pStart = uS2
                If pGR.UseProxy.ToUpper = "YES" Then
                    'pHost
                    uS1 = vString.ToUpper.IndexOf("PROXY NAME", pStart) + Len("PROXY NAME")
                    uS2 = vString.IndexOf("[", uS1) + 2
                    uE = vString.IndexOf("]", uS2)
                    uLen = (uE - uS2) + 1
                    pGR.ProxyName = Mid(vString, uS2, uLen)
                    pStart = uS2
                    'Port
                    uS1 = vString.ToUpper.IndexOf("PROXY PORT", pStart) + Len("PROXY PORT")
                    uS2 = vString.IndexOf("[", uS1) + 2
                    uE = vString.IndexOf("]", uS2)
                    uLen = (uE - uS2) + 1
                    pGR.ProxyPort = Mid(vString, uS2, uLen)
                    pStart = uS2
                    'UsePpass
                    uS1 = vString.ToUpper.IndexOf("PASSWORD WITH PROXY", pStart) + Len("PASSWORD WITH PROXY")
                    If vString.IndexOf("?", uS1) < vString.IndexOf("[", uS1) Then
                        pGR.UseProxyPass = "no"
                    Else
                        uS2 = vString.IndexOf("[", uS1) + 2
                        uE = vString.IndexOf("]", uS2)
                        uLen = (uE - uS2) + 1
                        pGR.UseProxyPass = Mid(vString, uS2, uLen)
                    End If
                    pStart = uS2
                    If pGR.UseProxyPass.ToUpper = "YES" Then
                        'Pusername
                        uS1 = vString.ToUpper.IndexOf("PROXY USERNAME", pStart) + Len("PROXY USERNAME")
                        uS2 = vString.IndexOf("[", uS1) + 2
                        uE = vString.IndexOf("]", uS2)
                        uLen = (uE - uS2) + 1
                        pGR.ProxyUserName = Mid(vString, uS2, uLen)
                        pStart = uS2
                        'Ppass
                        uS1 = vString.ToUpper.IndexOf("PROXY PASSWORD", pStart) + Len("PROXY PASSWORD")
                        uS2 = vString.IndexOf("[", uS1) + 2
                        uE = vString.IndexOf("]", uS2)
                        uLen = (uE - uS2) + 1
                        pGR.ProxyPassword = Mid(vString, uS2, uLen)
                        pStart = uS2
                    Else
                        pGR.ProxyUserName = ""
                        pGR.ProxyPassword = ""
                    End If
                Else
                    pGR.ProxyName = ""
                    pGR.ProxyPassword = ""
                    pGR.UseProxyPass = "no"
                    pGR.ProxyUserName = ""
                    pGR.UseProxy = "no"
                End If
                'Wu size
                uS1 = vString.ToUpper.IndexOf("ACCEPTABLE SIZE", pStart) + Len("ACCEPTABLE SIZE")
                uS2 = vString.IndexOf("[", uS1) + 2
                uE = vString.IndexOf("]", uS2)
                uLen = (uE - uS2) + 1
                pGR.WUSize = Mid(vString, uS2, uLen)
                pStart = uS2
            Else
                'Snippet of text is bad??
                'MsgBox("error!")
                GoTo NoInit
            End If
        Catch ex As Exception
            GoTo NoInit
        End Try
        lblS.Text = "Get advanced settings!"
        Try
Restart2:
            SetStartUpInfo()
            Dim dEnd As DateTime
            dEnd = DateTime.Now.AddSeconds(2)
            While DateTime.Now < dEnd
                Application.DoEvents()
            End While
            With pWriter
                .WriteLine("")   'name

                .WriteLine("")   'team   

                .WriteLine("")   'passkey

                If _bAskNet Then .WriteLine("")

                .WriteLine("")   'use proxy

                If pGR.UseProxy.ToUpper = "YES" Then
                    .WriteLine("")   'host

                    .WriteLine("")   'port

                    .WriteLine("")   'use password

                    If pGR.UseProxyPass.ToUpper = "YES" Then
                        .WriteLine("")   'user name

                        .WriteLine("")   'password

                    End If
                End If
                .WriteLine("") 'wu size

                .WriteLine("yes") 'Get advanced options

                While Not pConfigure.HasExited
                    pWriter.WriteLine("")
                End While
                'Standard settings work within the loop, advanced settings console output has a larger delay 
                'Solution?
                While Not _ConfigOutputReady
                    WaitMS(2000)
                    If Not _IsRunning And _ShouldRun Then
                        MsgBox("The console seems to have exited with an error, when you press OK the current operation will be repeated")
                        _ShouldRun = False
                        GoTo Restart2
                    End If
                End While

            End With
            If _SMPerror Then GoTo NoSMP
            'rtf.text not filled??? ' use output flag
            Dim vString As String = rtf.Text.ToString 'Getting values as enterd
            Dim pStart As Integer = vString.ToUpper.IndexOf("CONFIGURING FOLDING@HOME")
            Dim pEnd As Integer = vString.ToUpper.IndexOf("CONFIGONLY FLAG GIVEN")
            Dim HasAdvanced As Boolean = (vString.ToUpper.IndexOf("CORE PRIORITY") <> -1)
            Dim s1 As Integer, s2 As Integer, uE As Integer, uLen As Integer
            If Not HasAdvanced Then
                GoTo NoGo
            End If
            If vString.ToUpper.IndexOf("CORE PRIORITY") < vString.ToUpper.IndexOf("SERVICE") Then
                'Gpu client, start with core priority
                pGR.ClientType = sPGroup.eType.CoreFirst
                s1 = vString.ToUpper.IndexOf("CORE PRIORITY")
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.CorePriority = Mid(vString, s2, uLen)
                'cpu usage
                s1 = vString.ToUpper.IndexOf("CPU USAGE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.CpuUsage = Mid(vString, s2, uLen)
                'cpu usage
                s1 = vString.ToUpper.IndexOf("ASSEMBLY CODE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.DissableAssembly = Mid(vString, s2, uLen)
                'Pause battery
                s1 = vString.ToUpper.IndexOf("PAUSE IF BATTERY", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.PauseBattery = Mid(vString, s2, uLen)
                'CPint
                s1 = vString.ToUpper.IndexOf("BETWEEN CHECKPOINTS", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.CPInterval = Mid(vString, s2, uLen)
                'Memory
                s1 = vString.ToUpper.IndexOf("TO INDICATE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.MemoryIndication = Mid(vString, s2, uLen)
                'AdvMethods
                s1 = vString.ToUpper.IndexOf("SET -ADVMETHODS", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.AdvMethods = Mid(vString, s2, uLen)
                'Ignore deadline
                s1 = vString.ToUpper.IndexOf("IGNORE ANY DEADLINE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.IgnoreDeadline = Mid(vString, s2, uLen)
                'MachineID
                s1 = vString.ToUpper.IndexOf("MACHINE ID", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.MachineID = Mid(vString, s2, uLen)
                'AddRemove
                s1 = vString.ToUpper.IndexOf("SERVICE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.AddRemoveService = Mid(vString, s2, uLen)
                'Affinity lock
                s1 = vString.ToUpper.IndexOf("DISABLE CPU AFFINITY", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.DisableAffinty = Mid(vString, s2, uLen)
                'Params
                s1 = vString.ToUpper.IndexOf("CLIENT PARAMETERS", uE)
                s2 = vString.IndexOf("[", s1)
                uE = vString.IndexOf("]", s2)
                If uE - s2 = 1 Then
                    pGR.Parameters = ""
                Else
                    s2 += 2
                    uLen = (uE - s2) + 1
                    pGR.Parameters = Mid(vString, s2, uLen)
                End If
                'IP
                s1 = vString.ToUpper.IndexOf("IP ADDRESS", uE)
                s2 = vString.IndexOf("[", s1)
                uE = vString.IndexOf("]", s2)
                If uE - s2 = 1 Then
                    pGR.IPadress = ""
                Else
                    s2 += 2
                    uLen = (uE - s2) + 1
                    pGR.IPadress = Mid(vString, s2, uLen)
                End If
            Else
                'smp
                pGR.ClientType = sPGroup.eType.ServiceFirst
                'AddRemove
                s1 = vString.ToUpper.IndexOf("SERVICE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.AddRemoveService = Mid(vString, s2, uLen)
                s1 = vString.ToUpper.IndexOf("CORE PRIORITY")
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.CorePriority = Mid(vString, s2, uLen)
                'cpu usage
                s1 = vString.ToUpper.IndexOf("CPU USAGE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.CpuUsage = Mid(vString, s2, uLen)
                'cpu usage
                s1 = vString.ToUpper.IndexOf("ASSEMBLY CODE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.DissableAssembly = Mid(vString, s2, uLen)
                'Pause battery
                s1 = vString.ToUpper.IndexOf("PAUSE IF BATTERY", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.PauseBattery = Mid(vString, s2, uLen)
                'CPint
                s1 = vString.ToUpper.IndexOf("BETWEEN CHECKPOINTS", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.CPInterval = Mid(vString, s2, uLen)
                'Memory
                s1 = vString.ToUpper.IndexOf("TO INDICATE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.MemoryIndication = Mid(vString, s2, uLen)
                'AdvMethods
                s1 = vString.ToUpper.IndexOf("SET -ADVMETHODS", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.AdvMethods = Mid(vString, s2, uLen)
                'Ignore deadline
                s1 = vString.ToUpper.IndexOf("IGNORE ANY DEADLINE", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.IgnoreDeadline = Mid(vString, s2, uLen)
                'MachineID
                s1 = vString.ToUpper.IndexOf("MACHINE ID", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.MachineID = Mid(vString, s2, uLen)
                'Affinity lock
                s1 = vString.ToUpper.IndexOf("DISABLE CPU AFFINITY", uE)
                s2 = vString.IndexOf("[", s1) + 2
                uE = vString.IndexOf("]", s2)
                uLen = (uE - s2) + 1
                pGR.DisableAffinty = Mid(vString, s2, uLen)
                'Params
                s1 = vString.ToUpper.IndexOf("CLIENT PARAMETERS", uE)
                s2 = vString.IndexOf("[", s1)
                uE = vString.IndexOf("]", s2)
                If uE - s2 = 1 Then
                    pGR.Parameters = ""
                Else
                    s2 += 2
                    uLen = (uE - s2) + 1
                    pGR.Parameters = Mid(vString, s2, uLen)
                End If
                'IP
                s1 = vString.ToUpper.IndexOf("IP ADDRESS", uE)
                s2 = vString.IndexOf("[", s1)
                uE = vString.IndexOf("]", s2)
                If uE - s2 = 1 Then
                    pGR.IPadress = ""
                Else
                    s2 += 2
                    uLen = (uE - s2) + 1
                    pGR.IPadress = Mid(vString, s2, uLen)
                End If
            End If
        Catch ex As Exception
            GoTo NoInit
        End Try
        If DoGui Then ConfigureGUI()
        Exit Sub
NoInit:
        lblS.Text = "Err: " & Err.Description
        gbC.Enabled = True
        gbKeep.Enabled = True
        _ReadFailure = True
        Exit Sub
NoGo:
        lblS.Text = "Err: can not get advanced settings from console!"
        gbC.Enabled = True
        gbKeep.Enabled = True
        _ReadFailure = True
        Exit Sub
NoSMP:
        lblS.Text = "Err: smp has a problem!"
        gbC.Enabled = True
        gbKeep.Enabled = True
        Exit Sub
    End Sub
    Private _ReadFailure As Boolean = False
    Private Sub ConfigureGUI()
        lblS.Text = "Configuring GUI!"
        Application.DoEvents()
        Try
            cancelprocessing = True
            'Generate config form
            txtUserName.Text = pGR.Name
            txtTeamNumber.Text = pGR.Team
            'If Me.Client.PandeGroup.TeamNumber <> txtTeamNumber.Text Then txtTeamNumber.Text = Me.Client.PandeGroup.TeamNumber
            txtPassKey.Text = pGR.PassKey
            txtIP.Text = pGR.IPadress
            If Not NoCancel Then  'nocancel = setup, keep params from preferred settings!
                txtParam.Text = pGR.Parameters
            Else
                txtParam.Text = Client.PandeGroup.AdditionalParameters
            End If
            txtProxyName.Text = pGR.ProxyName
            txtProxyPort.Text = pGR.ProxyPort
            txtPusername.Text = pGR.ProxyUserName
            txtPpassword.Text = pGR.ProxyPassword
            If pGR.AskNet = "" Then
                cmbAskNet.Enabled = False
                cmbAskNet.Text = "no"
            Else
                cmbAskNet.Text = pGR.AskNet
            End If
            cmbProxy.Text = pGR.UseProxy
            cmbProxyPassword.Text = pGR.UseProxyPass
            'Check for service
            If pGR.ServiceMode Then
                lblService.Text = "Launch manually, remove  the service?"
            Else
                lblService.Text = "Launch automaticly, install as a service in this directory?"
            End If
            cmbService.Text = pGR.AddRemoveService
            cmbBigWu.Text = pGR.WUSize
            cmbCorePriority.Text = pGR.CorePriority
            nudCPUusage.Value = CInt(pGR.CpuUsage)
            nudMem.Maximum = CInt(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024)
            nudMem.Value = CInt(pGR.MemoryIndication)
            cmbDisableAssembly.Text = pGR.DissableAssembly
            cmbBattery.Text = pGR.PauseBattery
            cmbAdv.Text = pGR.AdvMethods
            cmbLocalDeadlines.Text = pGR.IgnoreDeadline
            cmbCpuAffinity.Text = pGR.DisableAffinty
            If pGR.MachineID <> Me.Client.PandeGroup.MachineID Then pGR.MachineID = Me.Client.PandeGroup.MachineID 'Override read settings for initial install
            cmbMachineID.Items.Clear()
            For x As Integer = 1 To 16
                cmbMachineID.Items.Add(x.ToString)
            Next
            For Each sID As String In Cfg.CfgManager.colTakenHWID
                cmbMachineID.Items.Remove(sID)
            Next
            If Not cmbMachineID.Items.Contains(pGR.MachineID) Then
                lblID.Text = "MachineID *Error*"
            Else
                lblID.Text = "MachineID"
            End If
            cmbMachineID.Text = pGR.MachineID
        Catch ex As Exception
            GoTo NoInit
        End Try
        lblS.Text = "Configuration read!"
        If Cfg.KeptSettings.bKeep Then
            Cfg.KeptSettings.KeptSettings(Me)
        End If
        If cmbProxy.Text.ToUpper = "NO" Then
            cmbProxyPassword.Enabled = False
            gbProxy.Enabled = False
        Else
            cmbProxyPassword.Enabled = True
            gbProxy.Enabled = True
            If cmbProxyPassword.Text.ToUpper = "YES" Then
                gbProxyPassword.Enabled = True
            Else
                gbProxyPassword.Enabled = False
            End If
        End If
        gbC.Enabled = True
        gbKeep.Enabled = True
        nudMem.Maximum = My.Computer.Info.TotalPhysicalMemory / 1024 / 1024
        cancelprocessing = False
        Exit Sub
NoInit:
        lblS.Text = "Err: " & Err.Description
    End Sub
#End Region
#Region "Basic form handling"
    Private boolCancel As Boolean = False
    Private _Done As Boolean = False
    Public ReadOnly Property CancelPressed() As Boolean
        Get
            Return boolCancel
        End Get
    End Property
    Public ReadOnly Property Done() As Boolean
        Get
            Return _Done
        End Get
    End Property
    Private _Client As New clsClientConfiguration.clsClientConfigs.sClientSettings.sClient
    Public Property Client() As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient
        Get
            Try
                Return _Client
            Catch ex As Exception
                Return Nothing
            End Try
        End Get
        Set(ByVal value As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient)
            _Client = value
        End Set
    End Property
    Private Sub cmdNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNext.Click
        Try
            pgBackUp = pGR   'Back up to first read settings 
            If txtUserName.TextLength = 0 Or txtUserName.Text.ToUpper = "ANONYMOUS" Then
                Dim rVal As MsgBoxResult = MsgBox("No username has been enterd, do you mind if I use my own?" & vbNewLine & vbNewLine & _
                                                  "No will configure the client with my name and team, yes will enable you to change the name, cancel will keep the [Anonymous] username!", MsgBoxStyle.Question + MsgBoxStyle.YesNoCancel)
                If rVal = MsgBoxResult.Yes Then
                    txtUserName.Focus()
                    Exit Sub
                ElseIf rVal = MsgBoxResult.No Then
                    txtUserName.Text = "Marvin_The_Martian"
                    txtTeamNumber.Text = "11314"
                    pgBackUp.Name = txtUserName.Text
                    pgBackUp.Team = txtTeamNumber.Text
                ElseIf rVal = MsgBoxResult.Cancel Then
                    txtUserName.Text = "Anonymous"
                    pgBackUp.Name = txtUserName.Text
                End If
            ElseIf txtTeamNumber.TextLength = 0 Or txtTeamNumber.Text = "0" Then
                Dim rVal As MsgBoxResult = MsgBox("No team has been enterd, do you mind if I add you to EOC Folding Team?" & vbNewLine & vbNewLine & _
                                                  "No will configure the client to join EOC Folding Team team, yes will enable you to change the team number, cancel will keep you in the team 0!", MsgBoxStyle.Question + MsgBoxStyle.YesNoCancel)
                If rVal = MsgBoxResult.Yes Then
                    txtTeamNumber.Focus()
                    Exit Sub
                ElseIf rVal = MsgBoxResult.No Then
                    txtTeamNumber.Text = "11314"
                    pgBackUp.Team = txtTeamNumber.Text
                ElseIf rVal = MsgBoxResult.Cancel Then
                    txtTeamNumber.Text = "0"
                End If
            End If
            gbC.Enabled = False
            gbKeep.Enabled = False
            'If chkRemember.Checked And chkRemember.Visible Then Cfg.KeptSettings.DoKeep(Me)
            With pgW
                .Name = txtUserName.Text
                .Team = txtTeamNumber.Text
                .PassKey = txtPassKey.Text
                .AskNet = cmbAskNet.Text
                .MachineID = cmbMachineID.Text
                .AddRemoveService = cmbService.Text
                If cmbService.Text = "yes" Then
                    If .ServiceMode Then
                        .ServiceCheck = sPGroup.eAddRemove.Manual
                    Else
                        .ServiceCheck = sPGroup.eAddRemove.Service
                    End If
                Else
                    .ServiceCheck = sPGroup.eAddRemove.Keep
                End If
                .AdvMethods = cmbAdv.Text
                .ClientType = pGR.ClientType
                .CorePriority = cmbCorePriority.Text
                .CPInterval = nudInterval.Value.ToString
                .CpuUsage = nudCPUusage.Value.ToString
                .DisableAffinty = cmbCpuAffinity.Text
                .DissableAssembly = cmbDisableAssembly.Text
                .IgnoreDeadline = cmbLocalDeadlines.Text
                .IPadress = txtIP.Text
                .CPInterval = nudInterval.Value.ToString
                .Parameters = txtParam.Text
                If Not .Parameters.ToUpper.Contains("-VERBOSITY 9") Then .Parameters &= " -verbosity 9"
                .MemoryIndication = nudMem.Value.ToString
                .PauseBattery = cmbBattery.Text
                .UseProxy = cmbProxy.Text
                .UseProxyPass = cmbProxyPassword.Text
                .ProxyName = txtProxyName.Text
                .ProxyPort = txtProxyPort.Text
                .ProxyPassword = txtPpassword.Text
                .ProxyUserName = txtPusername.Text
                .WUSize = cmbBigWu.Text
            End With
            'Try apply config
            lblS.Text = "Starting up.."
            SetStartUpInfo()
            Dim dEnd As DateTime
            dEnd = DateTime.Now.AddSeconds(1)
            While DateTime.Now < dEnd
                Application.DoEvents()
            End While
            With pWriter
                lblS.Text = "Configuring standard settings.."
                .WriteLine(pgW.Name)
                WaitMS(250)
                .WriteLine(pgW.Team)
                WaitMS(250)
                .WriteLine(pgW.PassKey)
                WaitMS(250)
                .WriteLine(pgW.AskNet)
                WaitMS(250)
                .WriteLine(pgW.UseProxy)
                WaitMS(250)
                If pgW.UseProxy.ToUpper = "YES" Then
                    .WriteLine(pgW.ProxyName)
                    WaitMS(250)
                    .WriteLine(pgW.ProxyPort)
                    WaitMS(250)
                    WriteLine(pgW.UseProxyPass)
                    WaitMS(250)
                    If pgW.UseProxyPass.ToUpper = "YES" Then
                        .WriteLine(pgW.ProxyUserName)
                        WaitMS(250)
                        .WriteLine(pgW.ProxyPassword)
                        dEnd = DateTime.Now.AddMilliseconds(500)
                        WaitMS(250)
                    End If
                End If
                .WriteLine(pgW.WUSize)
                WaitMS(250)
                .WriteLine("yes") 'adv options
                WaitMS(250)
                lblS.Text = "Configuring advanced options.."
                If pgW.ClientType = sPGroup.eType.ServiceFirst Then
                    .WriteLine(pgW.AddRemoveService)
                    WaitMS(250)
                    .WriteLine(pgW.CorePriority)
                    WaitMS(250)
                    .WriteLine(pgW.CpuUsage)
                    WaitMS(250)
                    .WriteLine(pgW.DissableAssembly)
                    WaitMS(250)
                    .WriteLine(pgW.PauseBattery)
                    WaitMS(250)
                    .WriteLine(pgW.CPInterval)
                    WaitMS(250)
                    .WriteLine(pgW.MemoryIndication)
                    WaitMS(250)
                    .WriteLine(pgW.AdvMethods)
                    WaitMS(250)
                    .WriteLine(pgW.IgnoreDeadline)
                    WaitMS(250)
                    .WriteLine(pgW.MachineID)
                    WaitMS(250)
                    .WriteLine(pgW.DisableAffinty)
                    WaitMS(250)
                    .WriteLine(pgW.Parameters)
                    WaitMS(250)
                    .WriteLine(pgW.IPadress)
                    WaitMS(250)
                    While Not pConfigure.HasExited
                        .WriteLine("")
                        WaitMS(250)
                    End While
                Else
                    .WriteLine(pgW.CorePriority)
                    WaitMS(250)
                    .WriteLine(pgW.CpuUsage)
                    WaitMS(250)
                    .WriteLine(pgW.DissableAssembly)
                    WaitMS(250)
                    .WriteLine(pgW.PauseBattery)
                    WaitMS(250)
                    .WriteLine(pgW.CPInterval)
                    WaitMS(250)
                    .WriteLine(pgW.MemoryIndication)
                    WaitMS(250)
                    .WriteLine(pgW.AdvMethods)
                    WaitMS(250)
                    .WriteLine(pgW.IgnoreDeadline)
                    WaitMS(250)
                    .WriteLine(pgW.MachineID)
                    WaitMS(250)
                    .WriteLine(pgW.AddRemoveService)
                    WaitMS(250)
                    .WriteLine(pgW.DisableAffinty)
                    WaitMS(250)
                    .WriteLine(pgW.Parameters)
                    WaitMS(250)
                    .WriteLine(pgW.IPadress)
                    WaitMS(250)
                    While Not pConfigure.HasExited
                        .WriteLine("")
                        WaitMS(250)
                        Application.DoEvents()
                    End While
                    While Not _ConfigOutputReady
                        Application.DoEvents()
                    End While
                    WaitMS(500) 'give outputhandler some extra time
                    If rtf.Text.ToUpper.Contains("PLEASE CHECK YOUR CONFIGURATION") Or rtf.Text.ToUpper.Contains("SOCK ERROR") Then
                        _SMPerror = True
                    End If
                End If
            End With
            pGR = New sPGroup
            ReadSettings(True)
            gbC.Enabled = False
            lblS.Text = "Comparing.."
            Dim bEqual As Boolean = True
            If Not txtIP.Text = pgW.IPadress Then
                _Cerror = eConfigError.IPadress
                bEqual = False
            ElseIf Not txtParam.Text = pgW.Parameters Then
                _Cerror = eConfigError.Parameters
                bEqual = False
            ElseIf Not txtPassKey.Text = pgW.PassKey Then
                _Cerror = eConfigError.Passkey
                bEqual = False
            ElseIf Not txtPpassword.Text = pgW.ProxyPassword Then
                _Cerror = eConfigError.ProxyPassword
                bEqual = False
            ElseIf Not txtProxyName.Text = pgW.ProxyName Then
                _Cerror = eConfigError.ProxyHost
                bEqual = False
            ElseIf Not txtProxyPort.Text = pgW.ProxyPort Then
                _Cerror = eConfigError.ProxyPort
                bEqual = False
            ElseIf Not txtPusername.Text = pgW.ProxyUserName Then
                _Cerror = eConfigError.ProxyUserName
                bEqual = False
            ElseIf Not txtTeamNumber.Text = pgW.Team Then
                _Cerror = eConfigError.Team
                bEqual = False
            ElseIf Not txtUserName.Text = pgW.Name Then
                _Cerror = eConfigError.UserName
                bEqual = False
            ElseIf Not cmbAdv.Text = pgW.AdvMethods Then
                _Cerror = eConfigError.AdvMethods
                bEqual = False
            ElseIf Not cmbAskNet.Text = pgW.AskNet Then
                _Cerror = eConfigError.AskNet
                bEqual = False
            ElseIf Not cmbBattery.Text = pgW.PauseBattery Then
                _Cerror = eConfigError.PauseBattery
                bEqual = False
            ElseIf Not cmbBigWu.Text = pgW.WUSize Then
                _Cerror = eConfigError.WuSize
                bEqual = False
            ElseIf Not cmbCorePriority.Text = pgW.CorePriority Then
                _Cerror = eConfigError.CorePriority
                bEqual = False
            ElseIf Not cmbCpuAffinity.Text = pgW.DisableAffinty Then
                _Cerror = eConfigError.CpuAffinity
                bEqual = False
            ElseIf Not cmbDisableAssembly.Text = pgW.DissableAssembly Then
                _Cerror = eConfigError.DisableAssembly
                bEqual = False
            ElseIf Not cmbLocalDeadlines.Text = pgW.IgnoreDeadline Then
                _Cerror = eConfigError.IgnoreDeadline
                bEqual = False
            ElseIf Not cmbMachineID.Text = pgW.MachineID Then
                _Cerror = eConfigError.MachineID
                bEqual = False
            ElseIf Not cmbProxy.Text = pgW.UseProxy Then
                _Cerror = eConfigError.UseProxy
                bEqual = False
            ElseIf Not cmbProxyPassword.Text = pgW.UseProxyPass Then
                _Cerror = eConfigError.UseProxyPassword
                bEqual = False
            End If
            'Check service
            If pgW.AddRemoveService.ToUpper = "YES" And _bWasRunning Then
                If Not pgW.ServiceCheck = sPGroup.eAddRemove.Keep Then
                    MsgBox("Because you changed the mode of a running client, it will now be restarted to ensure proper management and tracking.")
                    Client.GuiController.StopClient()
                    Client.GuiController.StartClient()
                End If
            End If
            If bEqual And Not _ReadFailure And Not _SMPerror Then
                lblS.Text = "Succes!"
                With _Client.PandeGroup
                    .AcceptedWUSize = pgW.WUSize
                    .AdditionalParameters = pgW.Parameters
                    .AskNetwork = pgW.AskNet
                    .CheckpointInterval = pgW.CPInterval
                    .CorePriority = pgW.CorePriority
                    .CpuUsage = pgW.CpuUsage
                    .DisableAffinitylock = pgW.DisableAffinty
                    .DisableAssembly = pgW.DissableAssembly
                    .ForceAdvMethods = pgW.AdvMethods
                    .IgnoreDeadline = pgW.IgnoreDeadline
                    .IPAdress = pgW.IPadress
                    .MachineID = pgW.MachineID
                    .MemoryUsage = pgW.MemoryIndication
                    .PassKey = pgW.PassKey
                    .PauseBattery = pgW.PauseBattery
                    .ProxyHost = pgW.ProxyName
                    .ProxyPassword = pgW.ProxyPassword
                    .ProxyPort = pgW.ProxyPort
                    .ProxyUserName = pgW.ProxyUserName
                    .TeamNumber = pgW.Team
                    .UseProxy = pgW.UseProxy
                    .UseProxyPassword = pgW.UseProxyPass
                    .UserName = pgW.Name
                    If .AdditionalParameters.ToUpper.Contains("-BETATEAM") Then bBetaTeam = True
                End With
                Try
                    llblLog.Visible = False
                Catch ex As Exception
                End Try
                If Not Cfg.CfgManager.colTakenHWID.Contains(pgW.MachineID) Then Cfg.CfgManager.colTakenHWID.Add(pgW.MachineID, pgW.MachineID.ToString)
                Cfg.CfgManager.ClientSettings.SaveConfig(Client)
                If Not bDialog Then
                    _Done = True
                Else
                    Me.Close()
                End If
            Else
                Select Case _Cerror
                    Case eConfigError.AddRemoveService
                        lblS.Text = "Error: Add/Remove service"
                    Case eConfigError.AdvMethods
                        lblS.Text = "Error: Advanced methods"
                    Case eConfigError.AskNet
                        lblS.Text = "Error: Ask before using network"
                    Case eConfigError.CorePriority
                        lblS.Text = "Error: Core priority"
                    Case eConfigError.CPInterval
                        lblS.Text = "Error: Check point interval"
                    Case eConfigError.CpuAffinity
                        lblS.Text = "Error: Cpu affinity"
                    Case eConfigError.CpuUsage
                        lblS.Text = "Error: Cpu usage"
                    Case eConfigError.DisableAssembly
                        lblS.Text = "Error: Disable Assembly"
                    Case eConfigError.IgnoreDeadline
                        lblS.Text = "Error: Ignore deadlines"
                    Case eConfigError.IPadress
                        lblS.Text = "Error: IP adress"
                    Case eConfigError.MachineID
                        lblS.Text = "Error: MachineID"
                    Case eConfigError.MemIndication
                        lblS.Text = "Error: Memory indication"
                    Case eConfigError.Parameters
                        lblS.Text = "Error: Additional parameters"
                    Case eConfigError.Passkey
                        lblS.Text = "Error: Passkey"
                    Case eConfigError.PauseBattery
                        lblS.Text = "Error: Pause on battery usage"
                    Case eConfigError.ProxyHost
                        lblS.Text = "Error: Proxy host"
                    Case eConfigError.ProxyPassword
                        lblS.Text = "Error: Proxy password"
                    Case eConfigError.ProxyPort
                        lblS.Text = "Error: Proxy port"
                    Case eConfigError.ProxyUserName
                        lblS.Text = "Error: Proxy username"
                    Case eConfigError.Team
                        lblS.Text = "Error: Team number"
                    Case eConfigError.UseProxy
                        lblS.Text = "Error: Use proxy"
                    Case eConfigError.UseProxyPassword
                        lblS.Text = "Error: User proxy password"
                    Case eConfigError.UserName
                        lblS.Text = "Error: User name"
                    Case eConfigError.WuSize
                        lblS.Text = "Error: Acceptable size of work units"
                    Case Else
                        If Not _SMPerror Then
                            lblS.Text = "Error: -read failure?-"
                        Else
                            lblS.Text = "Error: SMP has a problem!"
                        End If
                End Select
                llblLog.Visible = True
            End If
            gbC.Enabled = True
            gbKeep.Enabled = True
        Catch ex As Exception
            'Log to window

        End Try
    End Sub
    Public bDialog As Boolean = False
    Public NoCancel As Boolean = False
    Public DoLock As Boolean = True
    Public aClient As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient
    Private _bWasRunning As Boolean = True
    Private Sub frmConfig_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        If bDialog Then
            Try
                Me.Client = aClient
                If Client.PandeGroup.ServiceMode Then
                    If Client.GuiController.AttachToSC Then
                        If Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Paused Or Client.GuiController.ServiceState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eServiceState.Running Then _bWasRunning = True
                    Else
                        'Log to window 
                    End If
                Else
                    If Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Hidden Or Client.GuiController.wState = clsClientConfiguration.clsClientConfigs.sClientSettings.sClient.clsGUIController.eWindowState.Visible Then _bWasRunning = True
                End If
                Me.Text = aClient.GuiController.ClientLocation
                pGR.GUIType = aClient.GuiController.TypeOfClient
                pgBackUp.GUIType = aClient.GuiController.TypeOfClient
                pgW.GUIType = aClient.GuiController.TypeOfClient
                _Done = False
                For Each sID As String In Cfg.CfgManager.colTakenHWID
                    cmbMachineID.Items.Remove(sID)
                Next
                If NoCancel Then
                    cmdCancel.Enabled = False
                Else 'Add machine id from client to cmbbox, remove from taken hwid?
                    If cmbMachineID.Items.Contains(aClient.PandeGroup.MachineID) = False Then cmbMachineID.Items.Add(aClient.PandeGroup.MachineID)
                    If Cfg.CfgManager.colTakenHWID.Contains(aClient.PandeGroup.MachineID) Then Cfg.CfgManager.colTakenHWID.Remove(aClient.PandeGroup.MachineID)
                End If
                If DoLock Then LockByPreffered()
                Application.DoEvents()
                ReadSettings()
            Catch ex As Exception

        End Try
        End If
      
    End Sub
    Public Sub StartConfig(ByVal aClient As clsClientConfiguration.clsClientConfigs.sClientSettings.sClient, Optional ByVal NoCancel As Boolean = False, Optional ByVal DoLock As Boolean = True, Optional ByVal ShowKeep As Boolean = False)
        Try
            Me.Client = aClient
            Me.Text = aClient.GuiController.ClientLocation
            pGR.GUIType = aClient.GuiController.TypeOfClient
            pgBackUp.GUIType = aClient.GuiController.TypeOfClient
            pgW.GUIType = aClient.GuiController.TypeOfClient
            _Done = False
            For Each sID As String In Cfg.CfgManager.colTakenHWID
                cmbMachineID.Items.Remove(sID)
            Next
            If NoCancel Then
                cmdCancel.Enabled = False
            Else 'Add machine id from client to cmbbox, remove from taken hwid?
                If Not cmbMachineID.Items.Contains(aClient.PandeGroup.MachineID) Then cmbMachineID.Items.Add(aClient.PandeGroup.MachineID)
                If Cfg.CfgManager.colTakenHWID.Contains(aClient.PandeGroup.MachineID.ToString) Then Cfg.CfgManager.colTakenHWID.Remove(aClient.PandeGroup.MachineID.ToString)
            End If
            chkRemember.Visible = True
            If ShowKeep Then
                cancelprocessing = True
                gbKeep.Height = 235
                chkRemember.Checked = Cfg.KeptSettings.bKeep
            Else
                chkRemember.Visible = False
                gbKeep.Height = 210
            End If
            cancelprocessing = False
            If DoLock Then LockByPreffered()
            Me.Show()
            Application.DoEvents()
            ReadSettings()
        Catch ex As Exception
            Debug.Print(ex.Message)
        End Try
    End Sub
    Private Sub LockByPreffered()
        Dim sPref As clsClientConfiguration.clsClientConfigs.sPerferdConfig.sSingleClient = Cfg.CfgManager.PrefferedSettings.GetPreffered(_Client.GuiController.TypeOfClient)
        With sPref
            If .LockLaunchService Then cmbService.Enabled = False
            If .LockWuSize Then cmbCorePriority.Enabled = False
            If .LockPauseBattery Then cmbBattery.Enabled = False
            If .LockIgnoreLocalDeadlines Then cmbLocalDeadlines.Enabled = False
            If .LockDisableAssembly Then cmbDisableAssembly.Enabled = False
            If .LockDisableAffinityLock Then cmbCpuAffinity.Enabled = False
            If .LockAdvancedMethods Then cmbAdv.Enabled = False
            If .LockAdditionalParameters Then txtParam.Enabled = False
        End With
    End Sub
    Private Sub llblLog_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles llblLog.LinkClicked
        If rtf.TextLength = 0 Then Exit Sub
        Dim nLog As New frmLogOutput
        nLog.rtf.Text = rtf.Text
        nLog.ShowDialog(Me)
    End Sub
    Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
        'Cancel, coltakenhwid has item machineid for this client removed, use pgr
        If Not Cfg.CfgManager.colTakenHWID.Contains(pGR.MachineID.ToString) Then Cfg.CfgManager.colTakenHWID.Add(pGR.MachineID, pGR.MachineID.ToString)
        If bDialog Then
            Me.Close()
        Else
            boolCancel = True
        End If
    End Sub
#End Region
#Region "Proxy gb"
    Private Sub cmbProxy_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'If cancelProcessing Then Exit Sub
        If cmbProxy.Text.ToUpper = "NO" Then
            cmbProxyPassword.Enabled = False
            gbProxy.Enabled = False
        Else
            cmbProxyPassword.Enabled = True
            gbProxy.Enabled = True
            If cmbProxyPassword.Text.ToUpper = "YES" Then
                gbProxyPassword.Enabled = True
            Else
                gbProxyPassword.Enabled = False
            End If
        End If
    End Sub

    Private Sub cmbProxyPassword_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        'If cancelProcessing Then Exit Sub
        If cmbProxy.Text.ToUpper = "NO" Then
            cmbProxyPassword.Enabled = False
            gbProxy.Enabled = False
        Else
            cmbProxyPassword.Enabled = True
            gbProxy.Enabled = True
            If cmbProxyPassword.Text.ToUpper = "YES" Then
                gbProxyPassword.Enabled = True
            Else
                gbProxyPassword.Enabled = False
            End If
        End If
    End Sub
#End Region
#Region "Input filters for textboxes"
    Private Sub txtTeamNumber_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If (Not (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9)) Xor (Not (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9)) Xor Not e.KeyCode = Keys.Back Then
            e.SuppressKeyPress = True
        End If
    End Sub
    Private Sub txtProxyPort_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If (Not (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9)) Xor (Not (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9)) Xor Not e.KeyCode = Keys.Back Then
            e.SuppressKeyPress = True
        End If
    End Sub
    Private Sub txtUserName_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Tab Then
            e.SuppressKeyPress = True
        ElseIf e.KeyCode = Keys.Space Then
            e.SuppressKeyPress = True
            txtUserName.Text = txtUserName.Text & "_"
        ElseIf e.KeyCode = Keys.Enter Then
            txtTeamNumber.Focus()
        End If
    End Sub
#End Region

    Private Sub chkRemember_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkRemember.CheckedChanged
        If cancelprocessing Then Exit Sub
        If chkRemember.Checked Then
            Cfg.KeptSettings.DoKeep(Me)
        Else
            Cfg.KeptSettings.bKeep = False
        End If
    End Sub
End Class
